package com.meritit.test.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

public class ForkJoinWork extends RecursiveTask<Long>{

	private long start;
	
	private long end;
	
	public static final long circle = 100000L;
	
	
	public ForkJoinWork(long start, long end) {
		this.start = start;
		this.end = end;
	}
	
	
	@Override
	protected Long compute() {
		
		long length = end - start;
		
		if(length <= circle) {
			long sum = 0;
			for(long i = start; i <= end; i++) {
				sum += i;
			}
			return sum;
		}else {
			long middle = (end + start) / 2;
			ForkJoinWork right = new ForkJoinWork(middle, end);
			right.fork();
			ForkJoinWork left = new ForkJoinWork(start, middle);
			left.fork();
			
			return left.join() + right.join();
		}
	}
	
	
	public static void main(String[] args) {
		/*long l = System.currentTimeMillis();
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		ForkJoinWork fjw = new ForkJoinWork(0, 1000);
		long result = forkJoinPool.invoke(fjw);
		long l1 = System.currentTimeMillis();
        System.out.println("invoke = " + result +"  time: " + (l1-l));*/
		
		
		long l = System.currentTimeMillis();
		long reduce = LongStream.rangeClosed(0, 1000).parallel().reduce(0, Long::sum);
		System.out.println(reduce);
		
	}

}
